package com.mallcai.bigdata.ladon.service.report.impl;

import com.alicp.jetcache.AutoReleaseLock;
import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.CreateCache;
import com.mallcai.bigdata.ladon.service.report.IReportQueryStatisticService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author feixy
 * @version 1.0
 * @date 2019-09-06 17:06
 */
@Slf4j
@Service
public class ReportQueryStatisticService implements IReportQueryStatisticService {

    @CreateCache(name = "report.statistic-", cacheType = CacheType.REMOTE, expire = 1, timeUnit = TimeUnit.HOURS)
    private Cache<String, ReportStatisticDTO> cache;

    @CreateCache(name = "report.statistic.lock-", cacheType = CacheType.REMOTE)
    private Cache<String, Long> cacheLock;

    @Override
    public ReportStatisticDTO getStatistic(String code) {
        return cache.computeIfAbsent(code, key-> new ReportStatisticDTO());
    }

    @Override
    public void incErrorCall(String code) {
        try(AutoReleaseLock lock = cacheLock.tryLock(code,2, TimeUnit.SECONDS)){
            if(lock != null){
                cache.put(code, getStatistic(code).incErrorCall());
                return;
            }
        }
        log.warn("获取报表分布式锁失败:[code:{}]", code);
    }

    @Override
    public void resetErrorCall(String code) {
        try(AutoReleaseLock lock = cacheLock.tryLock(code, 2,TimeUnit.SECONDS)){
            if(lock != null){
                cache.put(code, new ReportStatisticDTO());
                return;
            }
        }
        log.warn("获取报表分布式锁失败:[code:{}]", code);
    }
}
